package com.qf.listen;

import com.qf.pojo.RedisKey;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class EmailListen {

    private static final Logger logger = LoggerFactory.getLogger(EmailListen.class);

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    RedisTemplate redisTemplate;

    @RabbitListener(queues = "email-queue")
    public void listenEmail(Map map, Channel channel, Message message){
        //邮件的发送
        String email = map.get("email").toString();
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(email);
            simpleMailMessage.setSubject("千锋邮件验证码");

            StringBuffer code=new StringBuffer();

            for (int i=0;i<4;i++){
                code.append(new Random().nextInt(10));
            }

            simpleMailMessage.setText(code.toString());
            javaMailSender.send(simpleMailMessage);
            redisTemplate.opsForValue().set(RedisKey.CODE+email,code.toString(),5, TimeUnit.MINUTES);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            logger.error("rabbitmq监听邮件发送出现异常！"+e.getMessage()+"发送的邮箱为："+email);
        }

    }
}
